package com.future.mayi.utils;

import android.content.Context;

import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.HttpRequest;
import com.future.baselib.utils.StringUtils;
import com.future.mayi.app.App;
import com.future.mayi.response.UploadFileResponse;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/8/20.
 */

public class UploadListImgUtils {

    private Context mContext;
    private UploadListener mUploadListener;
    private List<String> uploadImgList;
    private List<String> uploadUrlList;

    public UploadListImgUtils(Context context, UploadListener uploadListener) {
        this.mContext = context;
        this.mUploadListener = uploadListener;
    }

    public void startUpload(List<String> imgLists) {
        this.uploadImgList = imgLists;
        upload();
    }

    private void upload() {

        if (uploadImgList == null || uploadImgList.size() == 0) {
            String imgString = "";
            if (uploadUrlList != null && uploadUrlList.size() > 0) {
                for (String url : uploadUrlList) {
                    imgString = imgString + url + ",";
                }
            }
            if (imgString.length() > 0) {
                imgString = imgString.substring(0, imgString.length() - 1);
            }
            mUploadListener.uploadSucceed(imgString);
            return;
        }

        if (uploadUrlList == null) {
            uploadUrlList = new ArrayList<>(uploadImgList.size());
        }

        new HttpRequest<UploadFileResponse>()
                .with(mContext)
                .setApiCode(ApiCst.upload)
                .setFile(new File(uploadImgList.get(0)))
                .addFileParam("token", App.getToken(mContext))
                .setListener(new HttpRequest.OnNetworkListener<UploadFileResponse>() {
                    @Override
                    public void onSuccess(UploadFileResponse response) {
                        uploadImgList.remove(0);
                        uploadUrlList.add(response.getPhoto());
                        upload();
                    }

                    @Override
                    public void onFail(String message, UploadFileResponse response) {
                        if (mUploadListener != null) {
                            mUploadListener.uploadFailed(message);
                        }
                    }
                })
                .upload(new UploadFileResponse());
    }

    public interface UploadListener {

        void uploadSucceed(String imgString);

        void uploadFailed(String message);
    }

}
